package com.epam.client.backingbeans;

import javax.ejb.EJB;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;

import com.epam.DAO.ClientDAO;
import com.epam.DAO.RequestDAO;
import com.epam.entity.Client;
import com.epam.entity.Request;
import com.epam.entity.Status;

public class ClosedRequestBean {

	@EJB
	private RequestDAO requestDAO;
	@EJB
	private ClientDAO clientDAO;

	private DataModel<Request> requests;

	private int firstRow;
	private int totalPages;
	private int currentPage;

	private int rowsPerPage = 5;
	private int totalRows;

	public ClosedRequestBean() {
		requests = new ListDataModel<Request>();
	}

	public void pageFirst() {
        page(0);
    }

	public void pageNext() {
        page(firstRow + rowsPerPage);
    }

	public void pagePrevious() {
        page(firstRow - rowsPerPage);
    }

	public void pageLast() {
        page(totalRows - ((totalRows % rowsPerPage != 0) ? totalRows % rowsPerPage : rowsPerPage));
    }

    private void page(int firstRow) {
        this.firstRow = firstRow;
    }

	public int getTotalRows() {
		return totalRows;
	}

	public int getFirstRow() {
		return firstRow;
	}

	public int getRowsPerPage() {
		return rowsPerPage;
	}

	public int getCurrentPage() {
		return currentPage;
	}

	public int getTotalPages() {
		return totalPages;
	}

	public DataModel<Request> getRequests() {
		Client client = clientDAO.read();
		requests.setWrappedData(requestDAO.getUserRequests(client, firstRow,
				rowsPerPage, Status.CLOSED, Status.CANCELLED));

		totalRows = requestDAO.getUserRequestsCount(client, Status.CLOSED,
				Status.CANCELLED);
		// Set currentPage, totalPages and pages.
		currentPage = (totalRows / rowsPerPage)
				- ((totalRows - firstRow) / rowsPerPage) + 1;
		totalPages = (totalRows / rowsPerPage)
				+ ((totalRows % rowsPerPage != 0) ? 1 : 0);

		return requests;
	}

}
